package com.googlecode.imanager.client.action;

import java.util.Map;

import com.googlecode.imanager.client.Application;
import com.googlecode.imanager.client.Control;
import com.googlecode.imanager.client.bridge.BridgeManager;
import com.googlecode.imanager.client.io.HttpRequest;
import com.googlecode.imanager.client.io.Path;
import com.googlecode.imanager.client.io.HttpRequest.RequestType;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class HttpAction extends FlowAction {

    private static final long serialVersionUID = 1L;

    private Path path;
    private String method;
    private RequestType type;
    
    public HttpAction() {
        method = "POST";
        type = RequestType.AJAX;
    }
    
    @Override
    protected void doExecute(Control sender){
        if (BridgeManager.getInstance().executeAction(this, sender)){
            // Action handled by bridge implementation
            return;
        }
        sendToServer(sender, getFlowTarget(sender), null);
    }

    protected void sendToServer(final Control sender, Control rootControl, Map<String, Object> parameters) {
        Application app = sender.getApplication();
        if (app == null){
            throw new IllegalStateException("no application is running");
        }
        
        app.httpCall(
            new HttpRequest(path, method, type, rootControl, parameters){

                @Override
                public void onFailure(Throwable e) {
                    HttpAction.this.onFailure(sender, e);
                }

                @Override
                public void onSuccess(Object result) {
                    HttpAction.this.onSuccess(sender, result);
                }
                
            });
    }

    public Path getPath() {
        return path;
    }

    public void setPath(Path path) {
        this.path = path;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public RequestType getType() {
        return type;
    }

    public void setType(RequestType type) {
        this.type = type;
    }  
    
    
}
